
from PyQt5.QtGui import QColor, QFont
from qgis._core import QgsFillSymbol, QgsLineSymbol, QgsMarkerSymbol, \
    QgsSingleSymbolRenderer, QgsPalLayerSettings, QgsTextFormat, QgsTextBufferSettings, QgsWkbTypes, \
    QgsVectorLayerSimpleLabeling, QgsRendererCategory, QgsCategorizedSymbolRenderer, QgsRuleBasedRenderer, QgsSymbol
from .layer_config import LAYER_STYLES


def apply_fixed_style(layer):
    # 使用预定义配置
    # fields=layer.fields()
    # for field in fields:
    #     print(f"fiels:",field)
    # features=layer.getFeatures()
    # for feature in features:
    #     # 访问要素的属性
    #     attributes = feature.attributes()
    #     print(f"要素ID: {feature.id()}, 属性: {attributes}")
    #
    #
    #     # 访问特定字段的值 (假设字段名为"NAME")
    #     name = feature["HEIGHT"]  # 或者 feature.attribute("NAME")
    #     print(f"要素名称: {name}")
    #
    #     # 访问要素的几何形状
    #     geometry = feature.geometry()
    #     print(f"几何类型: {geometry.type()}")  # 0=点, 1=线, 2=面
    #     print(f"WKT表示: {geometry.asWkt()}")

    lname = layer.name().upper()
    print(f"应用样式到图层: {lname}")
    if lname == "ICEARE":
        apply_ice_coverage_style(layer)
    else:
        # 获取预定义样式配置
        style_config = LAYER_STYLES.get(lname)
        if not style_config:
            print(f"无预定义样式: {lname}")
            return

        # 根据图层类型应用不同样式
        try:
            if style_config["type"] == "fill":
                symbol = QgsFillSymbol.createSimple({
                    'color': style_config["color"],
                    'outline': style_config["outline"],
                    'outline_width': style_config["width"]
                })
            elif style_config["type"] == "line":
                symbol = QgsLineSymbol.createSimple({
                    'color': style_config["color"],
                    'width': style_config["width"],
                    'style': style_config.get("style", "solid")
                })
            elif style_config["type"] == "marker":
                symbol = QgsMarkerSymbol.createSimple({
                    'color': style_config["color"],
                    'size': style_config["size"],
                    'name': style_config["shape"],
                    'outline': style_config.get("outline", "black")
                })

            layer.setRenderer(QgsSingleSymbolRenderer(symbol))
            print(f"{lname}图层样式已应用: {style_config}")

            # 为等深线添加标签
            if lname == "DEPCNT":
                apply_label(layer, "VALDCO")

        except Exception as e:
            print(f"样式应用失败: {lname} - {str(e)}")

    # 刷新图层
    layer.triggerRepaint()


def apply_ice_coverage_style(layer):
    # 图层ICEARE
    if layer.name().upper() != "ICEARE":
        print(f"警告: 图层名称不是ICEARE，而是 {layer.name()}")
        return

    # 检查图层是否有HEIGHT字段
    if "HEIGHT" not in [field.name() for field in layer.fields()]:
        print("错误: 图层中没有HEIGHT字段")
        return

    renderer = QgsRuleBasedRenderer(QgsSymbol.defaultSymbol(layer.geometryType()))
    root_rule = renderer.rootRule()
    rules = [
        # (表达式, 颜色, 标签, 线宽)
        ('"HEIGHT" IS NULL', '#ff0000', '未定义', 0.26),
        ('"HEIGHT" < 0', '#ffffff', '无冰', 0.26),
        ('"HEIGHT" >= 0 AND "HEIGHT" < 0.1', '#d1e0f3', '薄冰', 0.26),
        ('"HEIGHT" >= 0.1 AND "HEIGHT" < 0.22', '#93b8e0', '中薄冰', 0.26),
        ('"HEIGHT" >= 0.22 AND "HEIGHT" < 0.5', '#5a90d1', '中等冰', 0.26),
        ('"HEIGHT" >= 0.5 AND "HEIGHT" < 0.7', '#2e64b8', '中厚冰', 0.26),
        ('"HEIGHT" >= 0.22', '#123c90', '厚冰', 0.26),
    ]
    # 创建分类渲染器
    for expression, color, label, width in rules:
        # 创建符号
        symbol = QgsFillSymbol.createSimple({
            'color': color,
            'outline_color': 'black',
            'outline_width': str(width)
        })

        # 创建规则
        rule = root_rule.children()[0].clone()
        rule.setLabel(label)
        rule.setFilterExpression(expression)
        rule.setSymbol(symbol)
        root_rule.appendChild(rule)

    # 删除默认规则
    root_rule.removeChildAt(0)

    # 设置渲染器到图层
    layer.setRenderer(renderer)

    # 刷新图层
    layer.triggerRepaint()

    print(f"已为图层 {layer.name()} 应用基于HEIGHT的表达式样式")
def apply_label(layer, field_name):
    # 为图层添加标签
    if field_name not in [f.name() for f in layer.fields()]:
        return

    settings = QgsPalLayerSettings()
    settings.fieldName = field_name
    settings.enabled = True

    # 文本格式
    format = QgsTextFormat()
    format.setSize(8)
    format.setColor(QColor("black"))

    font = QFont("Arial", 8)
    format.setFont(font)

    # 文本缓冲
    buffer_settings = QgsTextBufferSettings()
    buffer_settings.setEnabled(True)
    buffer_settings.setSize(0.5)
    buffer_settings.setColor(QColor("white"))
    format.setBuffer(buffer_settings)

    settings.setFormat(format)

    # 标签位置
    if layer.geometryType() == QgsWkbTypes.PointGeometry:
        settings.placement = QgsPalLayerSettings.AroundPoint
    elif layer.geometryType() == QgsWkbTypes.LineGeometry:
        settings.placement = QgsPalLayerSettings.Curved
    else:
        settings.placement = QgsPalLayerSettings.OverPoint

    labeling = QgsVectorLayerSimpleLabeling(settings)
    layer.setLabeling(labeling)
    layer.setLabelsEnabled(True)
    layer.triggerRepaint()